//
//  RBRegistVC.m
//  LittlePig
//
//  Created by Riber on 7/8/18.
//  Copyright © 2018年 Riber. All rights reserved.
//

#import "RBRegistVC.h"
#import <SMS_SDK/SMSSDK.h>
#import <BmobSDK/BmobQuery.h>
#import <BmobSDK/BmobObject.h>

#define MaxCount 12

@interface RBRegistVC () <UITextFieldDelegate>

@property (nonatomic,   weak) UIScrollView      *mainSV;

@property (nonatomic, strong) UIImageView       *logoIV;
@property (nonatomic, strong) UITextField   *mobileTF;
@property (nonatomic, strong) UITextField   *codeTF;
@property (nonatomic, strong) UITextField   *passTF;
@property (nonatomic, strong) UIButton          *sendBtn;
@property (nonatomic, strong) UIButton          *nextBtn;
@property (nonatomic, strong) UIButton          *agreeButton;
@property (nonatomic, strong) UIButton          *protocalBtn;
@property (nonatomic, strong) UILabel           *protocalLabel;
@property (nonatomic , assign) BOOL isSendCode;//是否已发送验证码

@end

@implementation RBRegistVC

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.passTF];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createUI];
}

#pragma mark mainSV的创建------------
- (UIScrollView *)mainSV {
    if (!_mainSV) {
        UIScrollView *mainSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        [self.view addSubview:mainSV];
        mainSV.contentSize = CGSizeMake(self.view.width, self.view.height);
        [mainSV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsZero);
        }];
        //        _mainSV.delegate = self;
        mainSV.showsVerticalScrollIndicator = NO;
        mainSV.showsHorizontalScrollIndicator = NO;
        
        _mainSV = mainSV;
    }
    return _mainSV;
}

- (void)createUI
{
    [self mainSV];
    
    self.logoIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, KHeight(280/2), KWidth(360/2), KHeight(120/2))];
    self.logoIV.centerX = self.view.centerX;
    self.logoIV.image = RBImageNamed(@"logo");
    [self.mainSV addSubview:self.logoIV];
    
    self.mobileTF = [self createTextFieldWithFrame:CGRectMake(KWidth(124/2), self.logoIV.maxY + KHeight(190/2), kSCREENW - KWidth(124), KHeight(88/2)) leftText:@"手机号"];
    self.mobileTF.placeholder = @"请输入手机号";
    self.mobileTF.text = self.registerMobilStr;
    [self.mobileTF setValue:[UIFont systemFontOfSize:KHeight(15)] forKeyPath:@"_placeholderLabel.font"];
    [self.mobileTF setValue:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forKeyPath:@"_placeholderLabel.textColor"];
    self.mobileTF.keyboardType = UIKeyboardTypePhonePad;
    [self.mainSV addSubview:self.mobileTF];
    
    self.codeTF = [self createTextFieldWithFrame:CGRectMake(self.mobileTF.x, self.mobileTF.maxY + KHeight(30/2), self.mobileTF.width, self.mobileTF.height) leftText:@"验证码"];
    self.codeTF.placeholder = @"请输入验证码";
    self.codeTF.delegate = self;
    [self.codeTF setValue:[UIFont systemFontOfSize:KHeight(15)] forKeyPath:@"_placeholderLabel.font"];
    [self.codeTF setValue:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forKeyPath:@"_placeholderLabel.textColor"];
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.mainSV addSubview:self.codeTF];
    
    self.sendBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.codeTF.maxX - KWidth(70), 0, KWidth(70), KHeight(30))];
    self.sendBtn.centerY = self.codeTF.centerY;
    self.sendBtn.backgroundColor = self.view.backgroundColor;
    [self.sendBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    self.sendBtn.titleLabel.font = [UIFont systemFontOfSize:KHeight(12)];
    self.sendBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.sendBtn.layer.borderWidth = 1;
    [self.sendBtn addTarget:self action:@selector(sendBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.sendBtn];
    
    self.passTF = [self createTextFieldWithFrame:CGRectMake(self.codeTF.x, self.codeTF.maxY + KHeight(15), self.codeTF.width, self.codeTF.height) leftText:@"密  码"];
    self.passTF.placeholder = @"请输入密码";
    [self.passTF setAttributedPlaceholder:[RBFactoryMethod addAttributed:self.passTF.placeholder attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:KWidth(15)], NSForegroundColorAttributeName:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00]} range:NSMakeRange(0, self.passTF.placeholder.length)]];
    
    //    [self.passTF setValue:[UIFont systemFontOfSize:KHeight(15)] forKeyPath:@"_placeholderLabel.font"];
    //    [self.passTF setValue:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forKeyPath:@"_placeholderLabel.textColor"];
    self.passTF.secureTextEntry = YES;
    [self.mainSV addSubview:self.passTF];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self.passTF];
    
    self.agreeButton = [RBFactoryMethod initWithNormalImageButtonFrame:CGRectMake(self.passTF.x, self.passTF.maxY + KHeight(10), KWidth(40), KHeight(90/2)) normalImageName:@"agree_normal" selectImageName:@"agree_select"];
    self.agreeButton.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    [self.agreeButton addTarget:self action:@selector(agreeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.agreeButton];
    
    self.protocalBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.agreeButton.maxX, self.agreeButton.y - KHeight(2), self.passTF.width - KWidth(40), KHeight(90/2))];
    [self.protocalBtn addTarget:self action:@selector(protocalBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.protocalBtn];
    
    self.protocalLabel = [RBFactoryMethod initWithLabelFrame:CGRectMake(self.agreeButton.maxX, self.agreeButton.y - KHeight(2), self.passTF.width - KWidth(40), KHeight(90/2)) andTextAlignment:NSTextAlignmentLeft andTextColor:[UIColor colorWithWhite:1 alpha:0.5] fontOfSystemSize:KWidth(14) isBold:NO];
    self.protocalLabel.numberOfLines = 0;
    self.protocalLabel.lineBreakMode = NSLineBreakByCharWrapping;
    self.protocalLabel.contentMode = UIViewContentModeTop;
    [self.mainSV addSubview:self.protocalLabel];
    self.protocalLabel.text = @"我已阅读并同意《服务协议》";
    
    self.protocalLabel.attributedText = [RBFactoryMethod addAttributed:self.protocalLabel.text attributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle], NSForegroundColorAttributeName:[UIColor colorWithWhite:1 alpha:0.5]} range:NSMakeRange(0, self.protocalLabel.text.length)];
    
    CGFloat height = [Helper heightOfString:self.protocalLabel.text font:[UIFont systemFontOfSize:KWidth(14)] width:self.passTF.width - KWidth(40)];
    self.protocalLabel.height = height;
    
    self.nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.passTF.x, self.protocalBtn.maxY + KHeight(30), self.passTF.width, KHeight(90/2))];
    [self.nextBtn setBackgroundColor:[UIColor whiteColor]];
    [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    self.nextBtn.layer.cornerRadius = KHeight(4);
    [self.nextBtn setTitleColor:[UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.00] forState:UIControlStateNormal];
    [self.nextBtn addTarget:self action:@selector(nextBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.nextBtn];
}

- (void)nextBtnClicked:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    if ([self.mobileTF.text length] == 0) {
        [MBProgressHUD showText:@"请输入手机号" toView:self.view];
        return;
    }
    
    if (![Helper justMobile:self.mobileTF.text]) {
        [MBProgressHUD showText:@"手机号码格式有误" toView:self.view];
        return;
    }
    
    if ([self.codeTF.text length] == 0) {
        [MBProgressHUD showText:@"请输入验证码" toView:self.view];
        return;
    }
    
    if ([self.passTF.text length] == 0) {
        [MBProgressHUD showText:@"请输入密码" toView:self.view];
        return;
    }
    if ([self.passTF.text length] < 6) {
        [MBProgressHUD showText:@"请输入不少于6位或超过12位的密码" toView:self.view];
        return;
    }
    if (!self.agreeButton.selected) {
        [MBProgressHUD showText:@"请同意注册协议" toView:self.view];
        return;
    }
    if (!self.isSendCode) {
        [MBProgressHUD showText:@"请先获取短信验证码" toView:self.view];
        return;
    }
    
    [MBProgressHUD showMessage:@"注册中..." toView:self.view];
    BmobQuery *query = [BmobQuery queryWithClassName:@"UserPerson"];
    [query whereKey:@"phone" equalTo:self.mobileTF.text];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            if (array.count > 0) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                [MBProgressHUD showText:@"该账号已注册，请登录" toView:[UIApplication sharedApplication].keyWindow];
                [weakSelf.navigationController popViewControllerAnimated:YES];
                if (weakSelf.loginBlock) {
                    weakSelf.loginBlock(weakSelf.mobileTF.text);
                }
            } else {
                [SMSSDK commitVerificationCode:self.codeTF.text phoneNumber:self.mobileTF.text zone:@"86" result:^(NSError *error) {
                    if (!error) {
                        BmobObject *object = [BmobObject objectWithClassName:@"UserPerson"];
                        [object setObject:weakSelf.mobileTF.text forKey:@"username"];
                        [object setObject:weakSelf.mobileTF.text forKey:@"phone"];
                        [object setObject:weakSelf.passTF.text forKey:@"psw"];
                        [object saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                            [MBProgressHUD hideHUDForView:self.view];
                            if (isSuccessful) {
                                [MBProgressHUD showText:@"注册成功，请登录" toView:[UIApplication sharedApplication].keyWindow];
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                                if (weakSelf.loginBlock) {
                                    weakSelf.loginBlock(weakSelf.mobileTF.text);
                                }
                            } else {
                                [MBProgressHUD showText:@"注册失败，请稍后尝试" toView:self.view];
                            }
                        }];
                        
                    } else {
                        [MBProgressHUD hideHUDForView:self.view];
                        [MBProgressHUD showText:@"验证码填写错误" toView:self.view];
                    }
                }];
            }
        } else {
            [MBProgressHUD hideHUDForView:weakSelf.view];
            [MBProgressHUD showText:@"注册失败，请稍后尝试" toView:self.view];
        }
    }];

//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [MBProgressHUD hideHUDForView:self.view];
//        [MBProgressHUD showText:@"注册成功" toView:self.view];
//    });
    
}

- (void)agreeButtonClick:(UIButton *)agreeButton {
    self.agreeButton.selected = !self.agreeButton.selected;
}

- (void)protocalBtnClicked:(UIButton *)btn
{

}

- (void)sendBtnClicked:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    [self.view endEditing:YES];
    if (self.mobileTF.text.length == 0) {
        [MBProgressHUD showText:@"请输入手机号" toView:self.view];

        return;
    }
    
    if ([Helper justMobile:self.mobileTF.text]) {
        __block int timeout=60; //倒计时时间
        [MBProgressHUD showMessage:@"发送中..." toView:self.view];
        //不带自定义模版
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.mobileTF.text zone:@"86"  result:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            if (!error) {
                weakSelf.isSendCode = YES;
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    if(timeout<=0){ //倒计时结束，关闭
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            [self.sendBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                            self.sendBtn.userInteractionEnabled = YES;
                        });
                    }else{
                        int seconds = timeout % 120;
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            //NSLog(@"____%@",strTime);
                            [UIView beginAnimations:nil context:nil];
                            [UIView setAnimationDuration:1];
                            [self.sendBtn setTitle:[NSString stringWithFormat:@"%@ S",strTime] forState:UIControlStateNormal];
                            self.sendBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
                            [UIView commitAnimations];
                            self.sendBtn.userInteractionEnabled = NO;
                        });
                        timeout--;
                    }
                });
                dispatch_resume(_timer);
            } else {
                [MBProgressHUD showText:@"短信验证码发送失败，请重新尝试" toView:self.view];
            }
        }];
    }
    else {
        [MBProgressHUD showText:@"请输入正确的手机号" toView:self.view];
    }
}

#pragma mark- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    
    if (textField == self.codeTF) {
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (string.length == 0) {
            return YES;
        }
        
        if (existedLength - selectedLength + replaceLength > 6) {
            return NO;
        }
        return YES;
    }
    
    return YES;
}

- (void)textFieldDidChange:(NSNotification *)notification {
    UITextField *passTF = notification.object;
    NSString *toBeString = passTF.text;
    if (toBeString.length > MaxCount) {
        passTF.text = [toBeString substringToIndex:MaxCount];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}


- (UITextField *)createTextFieldWithFrame:(CGRect)frame leftText:(NSString *)leftText
{
    UITextField *tf = [[UITextField alloc] initWithFrame:frame];
    tf.leftViewMode = UITextFieldViewModeAlways;
    tf.font = [UIFont systemFontOfSize:KWidth(16)];
    tf.textColor = [UIColor whiteColor];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth(160/2), tf.height)];
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KWidth(150/2), leftView.height)];
    leftLabel.text = leftText;
    leftLabel.numberOfLines = 0;
    leftLabel.lineBreakMode = NSLineBreakByWordWrapping;
    leftLabel.font = [UIFont systemFontOfSize:KHeight(16)];
    leftLabel.textColor = [UIColor whiteColor];
    leftLabel.adjustsFontSizeToFitWidth = YES;
    [leftView addSubview:leftLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, tf.height - 1, tf.width, 1)];
    line.backgroundColor = LINECOLOR;
    [tf addSubview:line];
    
    return tf;
}

@end
